import flash.display.BitmapData;
import flash.utils.ByteArray;

class SwfFS extends ByteArray {
	var files : Hash<ByteArray>;
	
	public function new () {
		super();
		
		files = new Hash<ByteArray>();
		
		// skip "SwfFS" plus version byte at the beginning
		var data = new ByteArray();
		position = 6;
		
		readBytes( data, 0, 0 );
		readData( data );
	}
	
	public function getFile( name : String ) : ByteArray {
		return files.get( name );
	}
	
	function readData ( data : ByteArray ) : Void {
		data.position = 0;

		var tableLength = data.readInt();
		var table = new ByteArray();
		data.readBytes( table, 0, tableLength );
		var content = new ByteArray();
		data.readBytes( content, 0, 0 );

		while( table.position < table.length - 1 ) {
			var nameLength = table.readByte();
			var name = table.readMultiByte( nameLength, "utf-8" );
			var offset = table.readInt();
			var len = table.readInt();
			var file = new ByteArray();
			content.position = offset;
			content.readBytes( file, 0, len );
			files.set( name, file );
		}
	}
}
